package dao.Implementation;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import Donnees.Client;
import Donnees.Pays;
import Util.HibernateUtil;
import dao.Interfaces.IClientDAO;

public class ClientDAO implements IClientDAO {
	public ClientDAO() {
	}

	public List<Client> selectAll() {
		List<Client> listeClient = new ArrayList<Client>();
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		
		listeClient.addAll(session.createQuery("from Client").list());
		
		session.flush();
		tx.commit();
		session.close();
		
		return listeClient;
	}
	
	public long insert(Client c) {
		Client clientTemp = c;
		Long msgId;

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		msgId = (Long) session.save(clientTemp);

		session.flush();
		tx.commit();
		session.close();

		return msgId;
	}

	public int delete(Client c) {
		Client clientTemp = c;
		int retour;

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		retour = session.createQuery(
				"delete from Client where nom='" + clientTemp.getNom() + "'")
				.executeUpdate();

		session.flush();
		tx.commit();
		session.close();

		return retour;
	}
	
	public Client getById(long id) {
		Client client = new Client();

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		client = (Client) session.createQuery("from Client where id='" + id+"'").list().get(0);

		session.flush();
		tx.commit();
		session.close();

		return client;
	}
}
